﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CdhpyScheduler.WebHost.PubMethod
{
    /// <summary>
    /// A custom wrapper around AutoMapper.Map
    /// </summary>
    public class MapperWrapper
    {
        /// <summary>
        /// AutoMapper
        /// </summary>
        /// <typeparam name="TA">source type</typeparam>
        /// <typeparam name="TB">destination type</typeparam>
        /// <param name="source">source</param>
        /// <returns>destination</returns>
        public static TB Map<TA, TB>(TA source)
        {
            // try to do the mapping
            try
            {
                return Mapper.Map<TA, TB>(source);
            }
            // catch AutoMapper's exception
            catch (Exception e)
            {
                // find the first InnerException that's not wrapped
                while (e is AutoMapperMappingException)
                {
                    e = e.InnerException;
                }

                //string log = $"AutoMapper.Mapper Exception: from {typeof(TA)} to {typeof(TB)}. ExceptionMessage: {e.Message}";
                return default(TB);
            }
        }
    }
}